<template>
  <div class="monthly-reports">
    <div class="header">
      <h3>月度工作总结</h3>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon> 提交月报
        </el-button>
        <el-button type="success" @click="showAISummaryDialog = true">
          <el-icon><MagicStick /></el-icon> 一键生成月报
        </el-button>
      </div>
    </div>

    <!-- 月度报告列表 -->
    <el-table :data="monthlyReports" style="width: 100%" v-loading="loading">
      <el-table-column prop="year" label="年份" width="100" />
      <el-table-column prop="month" label="月份" width="100">
        <template #default="{ row }">
          {{ getMonthName(row.month) }}
        </template>
      </el-table-column>
      <el-table-column prop="summary" label="总结摘要" width="300">
        <template #default="{ row }">
          <div class="text-content" :title="row.summary">
            {{ row.summary && row.summary.length > 50 ? row.summary.substring(0, 50) + '...' : row.summary }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="提交时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button size="small" @click="viewReport(row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建月报对话框 -->
    <el-dialog
      v-model="showDetailsDialog"
      :title="selectedReport ? `${selectedReport.year}年${selectedReport.month}月工作总结` : ''"
      width="900px"
      class="monthly-detail-dialog"
    >
      <div v-if="selectedReport" class="report-detail">
        <!-- 基本信息 -->
        <el-descriptions :column="3" border>
          <el-descriptions-item label="年份">{{ selectedReport.year }}</el-descriptions-item>
          <el-descriptions-item label="月份">{{ getMonthName(selectedReport.month) }}</el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ formatDate(selectedReport.created_at) }}</el-descriptions-item>
        </el-descriptions>

        <!-- 关联周报列表 -->
        <div v-if="linkedWeeklyReports.length > 0" class="linked-reports-section">
          <el-divider>
            <el-icon><Document /></el-icon>
            关联周报
            <el-tag type="primary" size="small" style="margin-left: 8px;">
              {{ linkedWeeklyReports.length }} 篇
            </el-tag>
          </el-divider>
          
          <div class="weekly-reports-list">
            <div 
              v-for="weekReport in linkedWeeklyReports" 
              :key="weekReport.id"
              class="week-report-item"
            >
              <div class="week-header">
                <div class="week-title">
                  <el-icon class="week-icon"><Calendar /></el-icon>
                  <span>第 {{ weekReport.week }} 周</span>
                </div>
                <div class="week-meta">
                  <el-tag v-if="weekReport.weekly_plan_id" type="primary" size="small" effect="plain">
                    <el-icon style="margin-right: 2px;"><Link /></el-icon>
                    已关联计划
                  </el-tag>
                  <span class="week-date">{{ formatDate(weekReport.created_at) }}</span>
                </div>
              </div>
              <div class="week-content">
                <div class="content-item">
                  <span class="label">
                    <el-icon><Trophy /></el-icon>
                    成就:
                  </span>
                  <span class="text">{{ weekReport.achievements }}</span>
                </div>
                <div class="content-item">
                  <span class="label">
                    <el-icon><Warning /></el-icon>
                    挑战:
                  </span>
                  <span class="text">{{ weekReport.challenges }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div v-else class="no-linked-reports">
          <el-empty description="本月报暂无关联的周报" :image-size="100" />
        </div>

        <!-- 月度总结 -->
        <el-divider>
          <el-icon><DocumentCopy /></el-icon>
          月度总结
        </el-divider>
        <div class="summary-content">{{ selectedReport.summary }}</div>
        
        <!-- 工作亮点 -->
        <el-divider>
          <el-icon><Star /></el-icon>
          工作亮点
        </el-divider>
        <div class="highlights-content">{{ selectedReport.highlights }}</div>
      </div>
    </el-dialog>

    <!-- AI 月度总结对话框 -->
    <el-dialog
      v-model="showAISummaryDialog"
      title="AI 一键生成月报"
      width="500px"
    >
      <el-form :model="aiSummaryForm" label-width="100px">
        <el-alert
          title="系统将自动汇总本月周报并生成月度总结"
          type="info"
          show-icon
          :closable="false"
          style="margin-bottom: 20px;"
        />
        <el-form-item label="年份">
          <el-select v-model="aiSummaryForm.year" placeholder="选择年份" style="width: 100%">
            <el-option v-for="year in years" :key="year" :label="year" :value="year" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="月份">
          <el-select v-model="aiSummaryForm.month" placeholder="选择月份" style="width: 100%">
            <el-option v-for="month in months" :key="month.value" :label="month.label" :value="month.value" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAISummaryDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="generateMonthlyReport" 
          :loading="generatingSummary">生成</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { 
  Plus, 
  MagicStick,
  Document,
  Calendar,
  Trophy,
  Warning,
  Link,
  DocumentCopy,
  Star
} from '@element-plus/icons-vue'

export default {
  name: 'MonthlyReports',
  components: {
    Plus,
    MagicStick,
    Document,
    Calendar,
    Trophy,
    Warning,
    Link,
    DocumentCopy,
    Star
  },
  setup() {
    const linkedWeeklyReports = ref([])
    const loadingLinkedReports = ref(false)
    const monthlyReports = ref([])
    const loading = ref(false)
    const showCreateDialog = ref(false)
    const showAISummaryDialog = ref(false)
    const showDetailsDialog = ref(false)
    const selectedReport = ref(null)
    const submitting = ref(false)
    const generatingSummary = ref(false)
    
    const reportForm = ref({
      year: new Date().getFullYear(),
      month: new Date().getMonth() + 1,
      summary: '',
      highlights: ''
    })
    
    const aiSummaryForm = ref({
      year: new Date().getFullYear(),
      month: new Date().getMonth() + 1
    })
    
    const reportFormRef = ref()
    
    const years = ref([2023, 2024, 2025, 2026])
    const months = ref([
      { label: '一月', value: 1 }, { label: '二月', value: 2 }, { label: '三月', value: 3 },
      { label: '四月', value: 4 }, { label: '五月', value: 5 }, { label: '六月', value: 6 },
      { label: '七月', value: 7 }, { label: '八月', value: 8 }, { label: '九月', value: 9 },
      { label: '十月', value: 10 }, { label: '十一月', value: 11 }, { label: '十二月', value: 12 }
    ])
    
    const rules = {
      year: [{ required: true, message: '请选择年份', trigger: 'change' }],
      month: [{ required: true, message: '请选择月份', trigger: 'change' }],
      summary: [{ required: true, message: '请填写月度总结', trigger: 'blur' }]
    }
    
    const fetchMonthlyReports = async () => {
      loading.value = true
      try {
        const response = await axios.get('/api/reports/monthly', {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        })
        monthlyReports.value = response.data
      } catch (error) {
        ElMessage.error('获取月度报告失败')
      } finally {
        loading.value = false
      }
    }
    
    const submitReport = async () => {
      if (!reportFormRef.value) return
      
      await reportFormRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          try {
            await axios.post('/api/reports/monthly', reportForm.value, {
              headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
            })
            
            ElMessage.success('月度报告提交成功')
            showCreateDialog.value = false
            resetForm()
            fetchMonthlyReports()
          } catch (error) {
            ElMessage.error('提交失败')
          } finally {
            submitting.value = false
          }
        }
      })
    }
    
    const generateMonthlyReport = async () => {
      generatingSummary.value = true
      try {
        const response = await axios.post('/api/reports/monthly/generate', {
          year: aiSummaryForm.value.year,
          month: aiSummaryForm.value.month
        }, {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        })

        ElMessage.success('AI月度总结已生成')
        showAISummaryDialog.value = false
        fetchMonthlyReports()
        
      } catch (error) {
        console.error('AI总结生成错误:', error)
        if (error.response) {
           if (error.response.status === 400) {
               ElMessage.warning(error.response.data.error || '该月无周报数据')
           } else {
               ElMessage.error(`生成失败: ${error.response.data.error || '服务器错误'}`)
           }
        } else {
          ElMessage.error('生成失败，请稍后重试')
        }
      } finally {
        generatingSummary.value = false
      }
    }

    const fetchLinkedWeeklyReports = async (report) => {
      loadingLinkedReports.value = true
      try {
        const response = await axios.get('/api/reports/weekly', {
          params: { year: report.year, month: report.month },
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        })
    
        // 过滤出关联到当前月报的周报
        linkedWeeklyReports.value = response.data.filter(
          wr => wr.monthly_report_id === report.id
        )
        
        console.log(`找到 ${linkedWeeklyReports.value.length} 个关联周报`)
      } catch (error) {
        console.error('获取关联周报失败:', error)
        ElMessage.error('获取关联周报失败')
      } finally {
        loadingLinkedReports.value = false
      }
    }

    const viewReport = async (report) => {
      selectedReport.value = report
      showDetailsDialog.value = true
      
      // 加载关联的周报
      await fetchLinkedWeeklyReports(report)
    }
    
    const getMonthName = (month) => {
      const monthObj = months.value.find(m => m.value === month)
      return monthObj ? monthObj.label : ''
    }
    
    const formatDate = (date) => {
      return new Date(date).toLocaleString('zh-CN')
    }
    
    const resetForm = () => {
      reportForm.value = {
        year: new Date().getFullYear(),
        month: new Date().getMonth() + 1,
        summary: '',
        highlights: ''
      }
    }
    
    onMounted(() => {
      fetchMonthlyReports()
    })
    
    return {
      monthlyReports,
      loading,
      showCreateDialog,
      showAISummaryDialog,
      showDetailsDialog,
      selectedReport,
      submitting,
      generatingSummary,
      reportForm,
      aiSummaryForm,
      reportFormRef,
      years,
      months,
      rules,
      submitReport,
      generateMonthlyReport,
      viewReport,
      getMonthName,
      linkedWeeklyReports,
      loadingLinkedReports,
      fetchLinkedWeeklyReports,
      formatDate
    }
  }
}
</script>

<style scoped>
.monthly-reports {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.text-content {
  word-break: break-word;
  line-height: 1.4;
  max-height: 3.2em;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.report-detail .summary-content,
.report-detail .highlights-content {
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
}
.linked-reports-section {
  margin-top: 20px;
}

.weekly-reports-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 400px;
  overflow-y: auto;
}

.week-report-item {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 3px solid #409eff;
  transition: all 0.3s ease;
}

.week-report-item:hover {
  background: #e3f2fd;
  transform: translateX(2px);
}

.week-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #ddd;
}

.week-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
  color: #409eff;
  font-size: 15px;
}

.week-icon {
  font-size: 18px;
}

.week-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.week-date {
  font-size: 12px;
  color: #909399;
}

.week-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.content-item {
  display: flex;
  gap: 8px;
  line-height: 1.6;
}

.content-item .label {
  display: flex;
  align-items: center;
  gap: 4px;
  min-width: 60px;
  font-weight: 500;
  color: #606266;
  font-size: 13px;
}

.content-item .text {
  flex: 1;
  color: #333;
  font-size: 13px;
}

.no-linked-reports {
  margin: 30px 0;
  text-align: center;
}

/* 对话框样式 */
.monthly-detail-dialog :deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
}
</style>